import React from 'react';
import { areaList } from '@vant/area-data'
const RentalAdd = () => {
    let navigate = React.$router.useNavigate();
    let [searchParams] = React.$router.useSearchParams();
    const [Business, setBusiness] = React.useState(React.$cookie.load('User') ?? {})
    const [card1, setCard1] = React.useState([])
    const [card2, setCard2] = React.useState([])
    // 证件照
    var card = []
    const [form] = React.$vant.Form.useForm()
    const [visible, setVisible] = React.useState(false)
    const [region, setRegion] = React.useState(Business.region_text)
    const [code, setCode] = React.useState([])
    const [product, setProduct] = React.useState(React.$cookie.load('product') ?? {
        name: '',
        rent: '',
        price: ''
    })
    // 日历
    const [DateShow, SetDateShow] = React.useState(false)

    // 最小天数
    const [day, SetDay] = React.useState(3)

    //3天后的日期
    const [end, SetEnd] = React.useState(new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000))

    // 回显日期
    const [endtime, SetEndTime] = React.useState(`${end.getFullYear()}/${end.getMonth() + 1}/${end.getDate()}`)

    //不含押金
    const [price, setPrice] = React.useState(0)

    // 含押金
    const [rent, setRent] = React.useState(0)


    React.useEffect(() => {
        Total()

    }, [])

    // 计算总价
    const Total = () => {
        // 日租金
        var price = product.price ?? 0

        // 押金
        var rent = product.rent ?? 0

        // 不含有押金
        var prices = (parseFloat(price) * day).toFixed(2)
        setPrice(prices)
        // 含押金
        var rents = (parseFloat(prices) + parseFloat(rent)).toFixed(2)
        setRent(rents)
    }

    // 确认日历时间
    const DateConfirm = (date) => {
        SetDateShow(false)
        // 结束时间
        SetEndTime(`${date.getFullYear()}/${date.getMonth() + 1}/${date.getDate()}`)
        // 更改默认时间
        SetEnd(date)

        // 当前日期
        var now = new Date();

        //相差天数
        var time = date - now; //时间戳

        var days = Math.ceil(time / (1000 * 60 * 60 * 24))
        SetDay(days)

    }

    // 确认地址
    const Confirm = (val, item) => {
        setVisible(false)
        let address = ''
        let [province, city, district] = item
        if (province) {
            address = province.text + '-';
            Business.province = province.value

        }
        if (city) {
            address += city.text + '-';
            Business.city = city.value
        }
        if (district) {
            address += district.text;
            Business.district = district.value
        }
        setCode(val)
        setRegion(address)
    }
    // 上传图片
    const upload = (file, name) => {
        if (file.length > 0) {
            if (name == 'card1') {
                setCard1(file)
                card[0] = file[0].file
                if (card2.length > 0) {
                    card[1] = card2[0].file
                }
            }
            if (name == 'card2') {
                setCard2(file)
                card[1] = file[0].file

                if (card1.length > 0) {
                    card[0] = card1[0].file
                }
            }
            form.setFieldsValue({ card: card })
        }
    }
    // 删除图片
    const del = (file, name) => {
        if (name == 'card1') {
            setCard1([])
            card[0] = null
        }
        if (name == 'card2') {
            setCard2([])
            card[1] = null
            if (card1.length > 0) {
                card[0] = card1[0].file
            }
        }
        form.setFieldsValue({ card: card })

    }
    const onFinish = async (values) => {
        if (day < 3) {
            React.$vant.Toast.fail('租车的日期不能小于3天')
            return false;
        }
        const RequestData = new FormData();
        let data = {
            busid: Business.id,
            proid: product.id,
            rent: product.rent,
            price: rent,
            endtime: endtime,
            address: values.address,
            province: Business.province,
            city: Business.city,
            district: Business.district,
        }

        // console.log(values.card)
        //判断是否修改头像
        RequestData.append("busid",Business.id);
        if (values.card.length > 0 && values.card[0]) {
            values.card.forEach(item => {
                RequestData.append('card[]', item)
            });

        }
        RequestData.append("data", JSON.stringify(data))
        let result = await React.$api.LeaseAdd(RequestData)
        if (result.code == 1) {
            React.$vant.Toast.success({
                message: result.msg,
                onClose: () => {
                    navigate('/business/order')
                }
            })
        } else {
            React.$vant.Toast.fail(result.msg)
        }
    }


    return (
        <>
            <React.$vant.NavBar
                title="产品租赁"
                leftText=""
                onClickLeft={() => navigate(-1)}
            />
            <React.$vant.Form
                form={form}
                onFinish={onFinish}

            >
                <React.$vant.Form.Item
                    rules={[{ required: true, message: '请选择商品' }]}
                    isLink
                    name='name'
                    label='租赁商品'
                    onClick={() => navigate('/lease/list?action=add')}
                    initialValue={product.name}
                >
                    <React.$vant.Input placeholder='请选择商品' readOnly />
                </React.$vant.Form.Item>

                <React.$vant.Form.Item
                    rules={[{ required: true, message: '请填写押金' }]}
                    name='rent'
                    label='押金'
                    initialValue={product.rent}
                >
                    <React.$vant.Input placeholder='请填写押金' readOnly />
                </React.$vant.Form.Item>

                <React.$vant.Form.Item
                    rules={[{ required: true, message: '请填写日供租金' }]}
                    name='price'
                    label='日供'
                    initialValue={product.price}
                >
                    <React.$vant.Input placeholder='请填写日供租金' readOnly />
                </React.$vant.Form.Item>

                <React.$vant.Form.Item
                    rules={[{ required: true, message: '请填写昵称' }]}
                    name='nickname'
                    label='昵称'
                    initialValue={Business.nickname}
                >
                    <React.$vant.Input placeholder='请输入昵称' />
                </React.$vant.Form.Item>
                <React.$vant.Form.Item
                    rules={[{ required: true, message: '请填写手机号码' }]}
                    name='mobile'
                    label='手机号码'
                    initialValue={Business.mobile}
                >
                    <React.$vant.Input placeholder='请输入手机号码' />
                </React.$vant.Form.Item>
                <React.$vant.Form.Item
                    isLink
                    label='地区选择'
                    onClick={() => setVisible(true)}
                >
                    <React.$vant.Input placeholder='请选择地区' readOnly value={region} />
                </React.$vant.Form.Item>
                <React.$vant.Popup visible={visible} onClose={() => setVisible(false)} position='bottom'>
                    <React.$vant.Area
                        title='地区'
                        value={code}
                        areaList={areaList}
                        onConfirm={Confirm}
                        onCancel={() => setVisible(false)}
                    ></React.$vant.Area>
                </React.$vant.Popup>
                <React.$vant.Form.Item
                    rules={[{ required: true, message: '请填写详细地址' }]}
                    name='address'
                    label='详细地址'
                >
                    <React.$vant.Input placeholder='请输入详细地址' />
                </React.$vant.Form.Item>

                {/* 租用时间 */}
                <React.$vant.Form.Item
                    isLink
                    label='租用时间'
                    onClick={() => SetDateShow(true)}
                >
                    <React.$vant.Input placeholder='请选择租用时间' readOnly value={endtime} />
                </React.$vant.Form.Item>

                {/* 日历 */}
                <React.$vant.Calendar
                    showConfirm={false}
                    visible={DateShow}
                    defaultDate={end}
                    onClose={() => { SetDateShow(false) }}
                    onConfirm={DateConfirm}
                />


                <React.$vant.Form.Item
                    name='card'
                    label='上传证件'
                    rules={[{
                        validator: (_, value) => {
                            if (card1.length > 0 && card2.length > 0) {
                                return Promise.resolve(true)
                            }
                            return Promise.reject(new Error('请选择证件照'))
                        },
                    }]}
                    className='lease_uploader'
                >
                    <div style={{ paddingBottom: '100px' }}>
                        <React.$vant.Uploader maxCount={1}
                            previewSize="90%"
                            name='card1' uploadIcon={<img src='/assets/images/img_wer.jpg' style={{ width: '100%', height: '100%', objectFit: 'cover' }} />}
                            onChange={(e) => upload(e, 'card1')}
                            onDelete={(e) => del(e, 'card1')}
                            value={card1}
                        />

                        <React.$vant.Uploader maxCount={1}
                            previewSize="90%" name='card2' uploadIcon={<img src='/assets/images/img_wer1.jpg' style={{ width: '100%', height: '100%', objectFit: 'cover' }} />}
                            onChange={(e) => upload(e, 'card2')}
                        />
                    </div>
                </React.$vant.Form.Item>
                <div className="zy_goods_foot dis_flex">
                    <div className="left">
                        <div>{day}天<b>￥<em>{price}</em></b></div>
                        <div className="tou_d">含押金￥{rent}</div>
                    </div>
                    <p>
                        <React.$vant.Button nativeType='submit' size="normal" type='warning' block>
                            立即申请
                        </React.$vant.Button>
                    </p>
                </div>
            </React.$vant.Form>
        </>
    )
}

export default RentalAdd;